package com.wangzhixuan.commons.filestorage.local;

import com.wangzhixuan.commons.Constant;
import com.wangzhixuan.commons.exception.BussinessException;
import com.wangzhixuan.commons.filestorage.BaseFileStorageService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.util.ImageUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 保存文件到本地
 *
 * @author lixin
 */
public class LocalFileStorageServerImpl extends BaseFileStorageService<LocalFileStorageConfig> {
    public LocalFileStorageServerImpl() {
        config = LocalFileStorageConfig.builder().path(Constant.UPLOAD_PATH).visitPath(Constant.VISIT_PATH).build();
        config.setStatus(true);
    }

    @Override
    protected String upload(MultipartFile file) throws IOException {
        if (StringUtils.isBlank(directory)) {
            if (checkFile(file.getInputStream())) {
                directory = "images";
            }
        }

        generateUrl();
        //保存到本地
        File localFile = new File(savePath + fileName);
        mkParentDirs(localFile);
        file.transferTo(localFile);
        return baseUrl;
    }

    private void generateUrl() {
        if (StringUtils.isBlank(directory)) {
            directory = fileType;
        }
        String dateStr = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now());
        savePath = config.getPath() + File.separator + directory + File.separator
                + dateStr + File.separator;
        //文件访问地址 不包含文件名
        baseUrl = config.getVisitPath() + "/" + directory + "/" + dateStr + "/";
    }

    /**
     * 创建父级目录
     *
     * @param file 文件
     */
    private void mkParentDirs(File file) {
        if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
            throw new BussinessException("创建文件夹失败");
        }
    }

    /**
     * 检查是否为图片
     * 仅支持bmp/gif/jpg/png
     *
     * @param in 文件流
     * @return true 是图片
     */
    private boolean checkFile(InputStream in) {
        try {
            Image image = ImageIO.read(in);
            return image != null;
        } catch (IOException ex) {
            return false;
        }
    }
}
